package com.bt7274.controller;

import com.bt7274.grace.result.GraceJSONResult;
import com.bt7274.pojo.UserExp;
import com.bt7274.pojo.bo.*;
import com.bt7274.pojo.vo.UserInfoVO;
import com.bt7274.pojo.vo.UserExpVO;
import com.bt7274.service.UserService;
import com.bt7274.service.impl.UserExpServiceImpl;
import com.bt7274.utils.SessionUtils;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import jdk.jshell.execution.Util;
import lombok.extern.slf4j.Slf4j;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

/**
 * @Data 2025/3/25 02:04
 * @Author hp,xyt
 * @Version 1.0
 * @Description UserController
 */

@Slf4j
@RestController
@RequestMapping("api/user")
@Tag(name = "用户管理", description = "用户注册登录，信息查询接口")
public class UserController {
    @Resource
    private UserService userService;
    @Autowired
    private UserExpServiceImpl userExpServiceImpl;

    @PostMapping("createOrUpdate")
    public GraceJSONResult createOrUpdate(@RequestBody UserBO userBO) {
        userService.createOrUpdate(userBO);
        return GraceJSONResult.ok();
    }

    /**
     * 用户注册
     * @param userRegisterBO 用户注册信息
     * @return GraceJSONResult
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "用户通过邀请码或免费注册")
    public GraceJSONResult register(@Valid @RequestBody UserRegisterBO userRegisterBO) {
        try {
            UserInfoVO userInfo = userService.register(userRegisterBO);
            return GraceJSONResult.ok(userInfo);
        } catch (Exception e) {
            log.error("用户注册失败: {}", e.getMessage(), e);
            return GraceJSONResult.fail(e.getMessage());
        }
    }

    /**
     * 用户修改密码（输入邮箱，原密码，新密码）
     *
     * @param userProfileUpdateBO:
     * @return GraceJSONResult
     * @author galland
     */
    @PutMapping("updatePassword")
    @Operation(summary = "用户更新密码",description = "用户输入邮箱、原始密码和新密码")
    public GraceJSONResult updatePassword(@Valid @RequestBody UserProfileUpdateBO userProfileUpdateBO) {
        try{
            if (userService.updatePassword(userProfileUpdateBO)){
                return GraceJSONResult.ok();
            }else  {
                return GraceJSONResult.errorMsg("更新密码失败");
            }
        }catch (Exception e){
            log.error("用户更新密码失败: {}", e.getMessage(), e);
            return GraceJSONResult.errorMsg(e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户使用用户名或邮箱登录")
    public GraceJSONResult login(@Valid @RequestBody UserLoginBO userLoginBO,
                                    HttpServletRequest request) {
        try {
            UserInfoVO userInfo = userService.login(userLoginBO);

            // 将用户信息保存到session中
            HttpSession session = request.getSession();
            session.setAttribute("userId", userInfo.getId());
            session.setAttribute("username", userInfo.getUsername());
            session.setAttribute("permissionGroup", userInfo.getPermissionGroup());

            return GraceJSONResult.ok(userInfo);
        } catch (Exception e) {
            log.error("用户登录失败: {}", e.getMessage(), e);
            return GraceJSONResult.errorMsg(e.getMessage());
        }
    }


    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    @Operation(summary = "获取当前用户信息", description = "根据session获取当前登录用户的信息")
    public GraceJSONResult getCurrentUserInfo() {
        try {
            // 获取用户ID
            String userId = SessionUtils.getCurrentUserId();
            if (userId == null) {
                return GraceJSONResult.errorMsg("用户未登录");
            }

            UserInfoVO userInfo = userService.getUserInfo(userId);
            // 获取用户经验数据
            UserExpVO userExp = userService.getUserExp(userId);
            // 设置用户经验数据
            userInfo.setUserExp(userExp);
            
            return GraceJSONResult.ok(userInfo);
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage(), e);
            return GraceJSONResult.errorMsg(e.getMessage());
        }
    }

    /**
     * 获取用户体验数据
     */
    @GetMapping("/exp")
    @Operation(summary = "获取用户体验数据", description = "获取当前用户的积分、上传下载量等数据")
    public GraceJSONResult getCurrentUserExp(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession(false);
            if (session == null) {
                return GraceJSONResult.errorMsg("用户未登录");
            }

            String userId = (String) session.getAttribute("userId");
            if (userId == null) {
                return GraceJSONResult.errorMsg("用户未登录");
            }

            UserExpVO userExp = userService.getUserExp(userId);
            return GraceJSONResult.ok(userExp);
        } catch (Exception e) {
            log.error("获取用户体验数据失败: {}", e.getMessage(), e);
            return GraceJSONResult.errorMsg(e.getMessage());
        }
    }

    /**
     * 获取指定用户信息（管理员接口）
     */
    @GetMapping("/info/{userId}")
    @Operation(summary = "获取指定用户信息", description = "管理员获取指定用户的信息")
    public GraceJSONResult getUserInfo(@PathVariable String userId) {
        try {
            UserInfoVO userInfo = userService.getUserInfo(userId);
            return GraceJSONResult.ok(userInfo);
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage(), e);
            return GraceJSONResult.errorMsg(e.getMessage());
        }
    }

    /**
     * 检查用户名是否可用
     */
    @GetMapping("/check-username/{username}")
    @Operation(summary = "检查用户名可用性", description = "检查用户名是否已被注册")
    public GraceJSONResult checkUsername(@PathVariable String username) {
        try {
            boolean exists = userService.existsByUsername(username);
            if (!exists) {
                return GraceJSONResult.ok("用户名可用");
            }else {
                return GraceJSONResult.errorMsg("用户名已存在");
            }
        } catch (Exception e) {
            log.error("检查用户名失败: {}", e.getMessage(), e);
            return GraceJSONResult.errorMsg(e.getMessage());
        }
    }

    /**
     * 检查邮箱是否可用
     */
    @GetMapping("/check-email/{email}")
    @Operation(summary = "检查邮箱可用性", description = "检查邮箱是否已被注册")
    public GraceJSONResult checkEmail(@PathVariable String email) {
        try {
            boolean exists = userService.existsByEmail(email);
            if (!exists) {
                return GraceJSONResult.ok("用户名可用");
            }else {
                return GraceJSONResult.errorMsg("用户名已存在");
            }
        } catch (Exception e) {
            log.error("检查邮箱失败: {}", e.getMessage(), e);
            return GraceJSONResult.errorMsg(e.getMessage());
        }
    }

    /**
     * 更新用户基本信息
     */
    @PutMapping("/profile")
    @Operation(summary = "更新用户基本信息", description = "更新用户名、邮箱、头像等基本信息")
    public GraceJSONResult updateUserProfile(@Valid @ModelAttribute UserProfileBO userProfileBO,
                                             HttpServletRequest request) {
        try {
            // 获取当前登录用户ID
            HttpSession session = request.getSession(false);
            if (session == null) {
                return GraceJSONResult.errorMsg("用户未登录");
            }

            String userId = (String) session.getAttribute("userId");
            if (userId == null) {
                return GraceJSONResult.errorMsg("用户未登录");
            }

            // 安全检查：确保只能更新自己的信息（除非是管理员）
            Integer permissionGroup = (Integer) session.getAttribute("permissionGroup");
            if (!userId.equals(userProfileBO.getId()) && permissionGroup < 6) { // 假设6及以上是管理员权限
                return GraceJSONResult.errorMsg("没有权限更新其他用户的信息");
            }

            // 执行更新
            UserInfoVO updatedUserInfo = userService.updateUserProfile(userProfileBO);

            // 如果是更新自己的信息，更新session中的用户名
            if (userId.equals(userProfileBO.getId()) && StringUtils.hasText(userProfileBO.getUsername())) {
                session.setAttribute("username", userProfileBO.getUsername());
            }

            return GraceJSONResult.ok(updatedUserInfo);
        } catch (Exception e) {
            log.error("更新用户信息失败: {}", e.getMessage(), e);
            return GraceJSONResult.errorMsg(e.getMessage());
        }
    }

}
